package vn.edu.fpt.taskmanager;

import java.io.File;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import vn.edu.fpt.taskmanager.logging.Log4jConfigurator;
import vn.edu.fpt.taskmanager.tasks.Task;
import android.app.Application;
import android.content.ContextWrapper;

/**
 * A class containing code for the whole application.
 * @author GaSjeuThjt
 */
public class TaskManagerApplication extends Application {

	private ArrayList<Task> taskList;
	private Logger logger = Logger.getLogger(TaskManagerApplication.class);

	/**
	 * Configure Log4j.
	 * @author GaSjeuThjt
	 */
	private void configureLog4j() {
		
		ContextWrapper cw = new ContextWrapper(getApplicationContext());
		File logFile = new File (cw.getFilesDir() + File.separator + "log4j.txt");
		
		logFile.delete(); // TODO this line if for debugging purpose and should be deleted later.
		
        String filePattern = "%-5p | %d{HH:mm:ss - dd/MM/yyyy} | %t | %c | %L | %m%n";
        int maxBackupSize = 10;
        long maxFileSize = 1024 * 1024;
 
        Log4jConfigurator.Configure(logFile.getAbsolutePath(), filePattern, maxBackupSize, maxFileSize);
	}

	/**
	 * Check whether an object is null or not.
	 * @param task the task object to be checked.
	 * @return True if the task object is null. Otherwise return False.
	 * @author GaSjeuThjt
	 * @see Task
	 */
	private boolean isNullObject(Task task) {
		return task == null;
	}
	
	/**
	 * Check whether the task name is empty or not.
	 * @param task the task object to be checked.
	 * @return True if the name of the task is empty. Otherwise return False.
	 * @author GaSjeuThjt
	 * @see Task
	 */
	private boolean isEmptyName(Task task) {
		return task.toString().equals("");
	}
	
	/**
	 * @author GaSjeuThjt
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		configureLog4j();
		
		/*
		 * If the task list is null then create it, 
		 * if not do nothing 
		 */
		if (taskList == null) {
			taskList = new ArrayList<Task>();
			
			// Logging
			logger.info("A new ArrayList is created for storing tasks");
		} else {
			// Logging
			logger.info("An ArrayList is already existed.");
		}
	}

	public ArrayList<Task> getTaskList() {
		return taskList;
	}

	/**
	 * Add a new task to the ArrayList, close this screen, return to view task screen  
	 * and refresh the screen for new tasks to appear. If the task object is null or
	 * it's name is empty the system will do nothing.
	 * @param task The task object to be added.
	 * @see Task
	 */
	public void addTask(Task task) {
		if (isNullObject(task) || isEmptyName(task)) {
			
			// Logging
			logger.warn("No new task was added because of null or empty name.");
			
			return;
		} else {
			taskList.add(task);
			
			// Logging
			logger.info("Task \"" + task.toString() + "\" is added.");
			
			AddTaskActivity.getActivity().finish();
		}
	}

}
